<?php

namespace application\controllers\base;

use peng\helpers\ArrayHelper;
use peng\helpers\Config;

/**
 * 控制器-基类
 *
 * @author peng.huang
 */
abstract class BaseController extends \peng\core\Controller {

    /**
     * 当前登录账号
     * 
     * @var object 
     */
    protected $_account;

    /**
     * 默认cookie名称
     * 
     * @var string 
     */
    protected $_defaultCookieName = '__h5';

    /**
     * 默认加密钥匙
     * 
     * @var string 
     */
    protected $_defaultEncryptedKey = '^@!%&!@%4';

    /**
     * 读取cookie中的账号信息
     * 
     * @return object
     */
    public function readAccount() {
        if (!isset($this->_account)) {
            $data = array();
            $config = Config::get('cookie', 'account');
            $str = $this->request->cookie(ArrayHelper::get($config, 'name', $this->_defaultCookieName));
            if (isset($str[0])) {
                $enctypt = ArrayHelper::get($config, 'encryption_key', $this->_defaultEncryptedKey);
                parse_str(base64_decode($str), $data);
            }

            if (!empty($data) && isset($data['key'], $data['loginname']) && $data['key'] === md5(md5($data['loginname'] . $enctypt))) {
                $this->_account = json_decode(json_encode($data), FALSE);
            }
        }

        return $this->_account;
    }

    /**
     * 写入账号信息到cookie中
     * 
     * @param array $account [账号信息]
     */
    public function writeAccount($account = NULL) {
        $expire = -100;
        $value = NULL;
        $config = Config::get('cookie', 'account');

        if (!empty($account)) {
            $enctypt = ArrayHelper::get($config, 'encryption_key', $this->_defaultEncryptedKey);
            $data = array(
                'aid' => $account['aid'],
                'loginname' => $account['loginname'],
                'loginAt' => $account['loginAt'],
                'key' => md5(md5($account['loginname'] . $enctypt))
            );
            $value = base64_encode(http_build_query($data));
            $expire = 0;
        }

        // 更新登录时间
        $cookieName = ArrayHelper::get($config, 'name', $this->_defaultCookieName);
        $this->response->addCookie($cookieName, $value, $expire);
    }

    /**
     * 清除cookie中的账号信息
     */
    public function clearAccount() {
        $this->writeAccount();
    }

}
